package uts.sdk.modules.lnxZhiyiTools;

import android.content.Context;
import android.util.Log;
import android.graphics.Bitmap;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

import com.dk.usbNfc.DKCloudID.IDCardData;
import com.dk.usbNfc.DeviceManager.DeviceManagerCallback;
import com.dk.usbNfc.DeviceManager.UsbNfcDevice;
import com.dk.usbNfc.Exception.DeviceNoResponseException;

import org.json.JSONException;
import org.json.JSONObject;

import static com.dk.usbNfc.DeviceManager.ComByteManager.ISO14443_P4;

/**
 * 德科身份证识别
 */
public class IDCardLocal {
    private static UsbNfcDevice usbNfcDevice = null;

    public static JSONObject idCardresult = new JSONObject();

    public static void initDevice(Context context){
        if (context == null){
            throw new RuntimeException("AppContext 为空");
        }
        if (usbNfcDevice == null) {
            usbNfcDevice = new UsbNfcDevice(context);
            usbNfcDevice.setCallBack(deviceManagerCallback);
        }
    }

    public static JSONObject getResult(){
        return idCardresult;
    }

    public static JSONObject clearResult(){
        return idCardresult = new JSONObject();
    }

    public static void startAutoSearchCard() {
        if (usbNfcDevice.usbHidManager.isClose()) {
            try {
                idCardresult.put("code",-1);
                idCardresult.put("message","USB设备未链接");
            } catch (JSONException e5) {
                throw new RuntimeException(e5);
            }
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //打开/关闭自动寻卡，100ms间隔，寻M1/UL卡
                    boolean isSuc = usbNfcDevice.startAutoSearchCard((byte) 20, ISO14443_P4);
                    if (isSuc) {
                        try {
                            idCardresult.put("code",2);
                            idCardresult.put("message","自动巡卡已打开");
                        } catch (JSONException err1) {
                            throw new RuntimeException(err1);
                        }
                    }
                    else {
                        try {
                            idCardresult.put("code",1);
                            idCardresult.put("message","自动巡卡已关闭");
                        } catch (JSONException err2) {
                            throw new RuntimeException(err2);
                        }
                    }
                } catch (DeviceNoResponseException e) {
                    try {
                        idCardresult.put("code",-2);
                        idCardresult.put("message","自动巡卡打开失败");
                    } catch (JSONException err3) {
                        throw new RuntimeException(err3);
                    }
                }
            }
        }).start();
    }

    public static void stoptAutoSearchCard() {
        if (usbNfcDevice.usbHidManager.isClose()) {
            try {
                idCardresult.put("code",-1);
                idCardresult.put("message","USB设备未链接");
            } catch (JSONException e1) {
                throw new RuntimeException(e1);
            }
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //打开/关闭自动寻卡，100ms间隔，寻M1/UL卡
                    boolean isSuc = usbNfcDevice.stoptAutoSearchCard();
                    if (isSuc) {
                        try {
                            idCardresult.put("code",2);
                            idCardresult.put("message","自动巡卡已关闭");
                        } catch (JSONException e2) {
                            throw new RuntimeException(e2);
                        }
                    }
                    else {
                        try {
                            idCardresult.put("code",2);
                            idCardresult.put("message","自动巡卡已打开");
                        } catch (JSONException e3) {
                            throw new RuntimeException(e3);
                        }
                    }
                } catch (DeviceNoResponseException e4) {
                    try {
                        idCardresult.put("code",-2);
                        idCardresult.put("message","自动巡卡打开失败");
                    } catch (JSONException e5) {
                        throw new RuntimeException(e5);
                    }
                }
            }
        }).start();
    }

    private static DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onReceiveConnectionStatus(boolean blnIsConnection) {
            if (blnIsConnection) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            byte versionsByts = usbNfcDevice.getDeviceVersions();
                            try {
                                idCardresult.put("code",2);
                                idCardresult.put("message","USB连接成功,版本号："+String.format("设备版本：%02x", versionsByts));
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                            try {
                                usbNfcDevice.closeRf();
                            } catch (DeviceNoResponseException e) {
                                e.printStackTrace();
                            }
                            startAutoSearchCard();
                        } catch (DeviceNoResponseException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
            else {
                try {
                    idCardresult.put("code",-1);
                    idCardresult.put("message","USB连接断开");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        @Override
        //寻到卡片回调
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            super.onReceiveRfnSearchCard(blnIsSus, cardType, bytCardSn, bytCarATS);
            if (!blnIsSus || cardType == UsbNfcDevice.CARD_TYPE_NO_DEFINE) {
                return;
            }


        }

        //身份证开始请求云解析回调
        @Override
        public void onReceiveSamVIdStart(byte[] initData) {
            super.onReceiveSamVIdStart(initData);
            idCardresult = new JSONObject();
            try {
                idCardresult.put("code",1);
                idCardresult.put("message","USB连接成功");
                idCardresult.put("resultCode",2);
                idCardresult.put("resultMessage","正在读卡，请勿移动身份证!");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }

        }

        //身份证云解析进度回调
        @Override
        public void onReceiveSamVIdSchedule(int rate) {
            super.onReceiveSamVIdSchedule(rate);
            try {
                idCardresult.put("resultCode",3);
                idCardresult.put("resultMessage","正在读取身份证信息，请勿移动身份证!");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            if (rate == 100) {
                try {
                    idCardresult.put("resultCode",4);
                    idCardresult.put("resultMessage","身份证读取成功");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        //身份证云解析异常回调
        @Override
        public void onReceiveSamVIdException(String msg) {
            super.onReceiveSamVIdException(msg);
            try {
                idCardresult.put("resultCode",5);
                idCardresult.put("resultMessage","身份证读取失败："+msg);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }

        //身份证云解析明文结果回调
        @Override
        public void onReceiveIDCardData(IDCardData idCardData) {
            super.onReceiveIDCardData(idCardData);
            String imgStr = "";
            if (null != idCardData.PhotoBmp){
                // if (null == bitmap) return null;
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                //把bitmap100%高质量压缩 到 output对象里
                idCardData.PhotoBmp.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                byte[] byteArray = outputStream.toByteArray();
                imgStr = Base64.encodeToString(byteArray, Base64.DEFAULT);
            }
            try {
                idCardresult.put("resultCode",6);
                //照片
                idCardresult.put("photo",imgStr.replaceAll("\\n",""));
                //户籍地
                idCardresult.put("address",idCardData.Address);
                //生日
                idCardresult.put("born",idCardData.Born);
                //发证机关
                idCardresult.put("grantDept",idCardData.GrantDept);
                //身份证号
                idCardresult.put("iDCardNo",idCardData.IDCardNo);
                //名称
                idCardresult.put("name",idCardData.Name);
                //民族
                idCardresult.put("nation",idCardData.Nation);
                //性别
                idCardresult.put("sex",idCardData.Sex);
                //有效期开始
                idCardresult.put("userLifeBegin",idCardData.UserLifeBegin);
                //有效期结束
                idCardresult.put("userLifeEnd",idCardData.UserLifeEnd);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            //显示身份证数据
            //            showIDCardData(idCardData);

        }
    };


}
